<?php
/**
 * Created by PhpStorm.
 * User: 睿
 * Date: 2017-11-01
 * Time: 15:51
 */

namespace app\store\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use PHPExcel;
use PHPExcel_IOFactory;

class Goods extends BasicAdmin
{
    public function _initialize()
    {
        //@lingyun   2018-01-04  一键登入门店
        if(!empty(input('storeid'))){           //门店id
            session('user.store_id',input('storeid'));
        }
        //@lingyun   2018-01-04  一键登入门店
    }
    /**
     * 指定当前数据表
     * @var string
     */
    public $table = 'StoreGoods';

    /**
     * 商品列表
     * @return array|string
     */
    public function index()
    {
        $this->title = '商品列表';
        $get = $this->request->get();

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_category c', 'g.cat_id=c.id', 'LEFT'],
        ];
        $store_id = session('user')['store_id'];

        $db = Db::name($this->table)->alias('a')->where('a.store_id', $store_id)->field('a.id,g.name,c.title,g.logo,a.onsale,a.stock,g.id as gid')->order('a.onsale', 'desc')->where('a.is_deleted', 0)->join($join);

        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        return parent::_list($db);
    }


    /**
     * 下架
     */
    public function forbid()
    {
        $this->table = 'store_goods_stock';
        if (DataService::update($this->table)) {
            $this->success("商品下架成功！", '');
        }
        $this->error("商品下架失败，请稍候再试！");
    }

    /**
     * 上架
     */
    public function resume()
    {
        $this->table = 'store_goods_stock';
        if (DataService::update($this->table)) {
            $this->success("商品上架成功！", '');
        }
        $this->error("商品上架失败，请稍候再试！");
    }

    /**
     * @Author  lingyun
     * @Desc    设置推荐商品
     */
    public function set_tuijian(){
        $post = input('post.');
        $res = db('store_goods_stock')->where('id',$post['id'])->update([$post['field']=>$post['value']]);
        $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
    }

    /**
     * 添加商品
     * @return array|string
     */

    public function add()
    {
        $store_id = session('user')['store_id'];
        if (request()->ispost()) {
            $insert = db('store_goods')->insert(['goods_id' => input('goods_id'), 'store_id' => $store_id, 'addtime' => time()]);
            if ($insert !== false)
                $this->success('商品添加成功！', '');
        } else {
            $db = db('goods')->select();

            //店里有了，就不再显示了
            foreach ($db as $key => $value) {
                $goods = db('store_goods')->where('store_id', $store_id)->where('goods_id', $value['id'])->where('is_deleted', 0)->find();
                if ($goods)
                    unset($db[$key]);
            }

            $this->assign('list', $db);

            return $this->_form($this->table, 'form');
        }

    }


    /**
     * 删除商品
     */
    public function del()
    {
        $goods = db($this->table)->find($this->request->post('id'));
        if ($goods['onsale'] == 1)
            $this->error('销售中商品禁止删除！');

        if (DataService::update($this->table)) {
            $this->success("商品删除成功！", '');
        }
        $this->error("商品删除失败，请稍候再试！");
    }


    /**
     * 入库
     */
    public function putin()
    {
        $store_id = session('user')['store_id'];
        if (request()->ispost()) {

            $post = input('post.');

            foreach ($post as $key => $value) {
                if ($key != 'id' && $key != 'num' && $value) {
                    //获取属性名称
                    $spec = db('goods_spec_detail')->find($key);

                    if ($goods_stock = db('store_goods_stock')->where('goods_spec_id', $key)->find()) {
                        $insert = db('store_goods_stock')->where('goods_spec_id', $key)->setInc('stock', $value);
                        $stock = $goods_stock['stock'];
                    } else {
                        $insert = db('store_goods_stock')->insert(['goods_id' => $post['id'], 'goods_spec_id' => $key, 'title' => $spec['title'], 'stock' => $value, 'store_id' => $store_id, 'addtime' => time()]);
                        $stock = 0;
                    }
                    $log = db('store_goods_log')->insert(['goods_id' => $post['id'], 'goods_spec_id' => $key, 'title' => $spec['title'], 'store_id' => $store_id, 'ruku_num' => $value, 'cur_stock' => $stock + $value, 'addtime' => time()]);


                }
                if ($key == 'num') {
                    if ($goods_stock = db('store_goods_stock')->where('goods_id', $post['id'])->find()) {
                        $insert = db('store_goods_stock')->where('goods_id', $post['id'])->setInc('stock', $value);
                        $stock = $goods_stock['stock'];
                    } else {
                        $insert = db('store_goods_stock')->insert(['goods_id' => $post['id'], 'goods_spec_id' => -1, 'stock' => $value, 'store_id' => $store_id, 'addtime' => time()]);
                        $stock = 0;
                    }
                    $log = db('store_goods_log')->insert(['goods_id' => $post['id'], 'goods_spec_id' => -1, 'store_id' => $store_id, 'ruku_num' => $value, 'cur_stock' => $stock + $value, 'addtime' => time()]);
                }

                if ($key != 'id' && $value) {
                    //冲减原料库存
                    $peifang = db('goods_yongliao')->where(['goods_id' => $post['id']])->select();
                    $spec_detail = db('goods_spec_detail')->find($key);

                    if ($peifang)
                        foreach ($peifang as $v) {
                            if ($spec_detail)
                                $sum[$v['material_id']][] = $v['num'] * $spec_detail['recipe_ratio'] * $value;
                            else
                                $sum[$v['material_id']][] = $v['num'] * $value;
                        }
                }
            }

            if (isset($sum)) {
                foreach ($sum as $kk => $vv)
                    $ret[$kk] = array_sum($vv);

                foreach ($ret as $kkk => $vvv) {
                    if ($vvv) {
                        $material_stock = db('store_material_stock')->where(['store_id' => $store_id, 'material_id' => $kkk])->find();
                        $mstock = db('store_material_stock')->where(['store_id' => $store_id, 'material_id' => $kkk])->setDec('stock', $vvv);
                        $mlog = db('store_material_log')->insert(['store_id' => $store_id, 'material_id' => $kkk, 'chuku_num' => $vvv, 'cur_stock' => $material_stock['stock'] - $vvv, 'addtime' => time()]);
                    }
                }
            }

            $this->success('商品入库成功！', '');
        } else {
            $store_goods_id = input('id');
            $store_goods = db($this->table)->where('id', $store_goods_id)->find();
            $goods = db('goods')->where('id', $store_goods['goods_id'])->find();

            if ($goods['is_spec'] == 1) {
                $spec = db('goods_spec_detail')->where('goods_id', $goods['id'])->select();

                $this->assign('spec', 1);//有规格
                $this->assign('list', $spec);
            } else {
                $this->assign('spec', 0);//没有规格
            }

            $this->assign('goods_id', $goods['id']);
            return $this->_form('goods_spec', 'putin');
        }
    }


    /**
     * 报警库存
     * @return array|string
     */
    public function warn()
    {
        $this->title = '报警库存';
        $get = $this->request->get();

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT'],
            ['ys_goods_category c', 'g.cat_id=c.id', 'LEFT'],
        ];

        $store_id = session('user')['store_id'];
        $map['a.stock'] = ['lt','a.warn_stock'];
        $map['a.store_id'] = ['eq',$store_id];
        $map['a.is_deleted'] = ['eq',0];

//        $db = Db::name('store_goods_stock')->alias('a')->where('a.store_id', $store_id)->field('a.*,g.name,c.title as ctitle,g.logo,g.id as gid,d.title as dtitle')->order('a.onsale', 'desc')->where('a.is_deleted', 0)->join($join);

        $db = Db::name('store_goods_stock')->alias('a')->where('a.store_id', $store_id)->where('a.stock','lt','a.warn_stock')->field('a.*,g.name,c.title as ctitle,g.logo,g.id as gid,d.title as dtitle')->order('a.onsale', 'desc')->where('a.is_deleted', 0)->join($join);

        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        $store = db('store')->find($store_id);

        $this->assign('store', $store);

        $warn = db('store_goods_stock')->where(['store_id'=>$store_id,'is_deleted'=>0,'is_diannei'=>1])->where('stock','lt','warn_stock')->select();
        $num = 0;//报警
        foreach ($warn as $value)
            if ($value['stock'] < $value['warn_stock'])
                $num++;

        if ($num > 0) {
            $this->assign('num', $num);
        }

        return parent::_list($db);
    }


    /**
     * 商品移动清单
     * @return array|string
     */
    public function li()
    {
        $store_id = session('user')['store_id'];

        $post = input();

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT'],
        ];

        $store_goods = db('store_goods_stock')->alias('a')->join($join)->field('g.name,d.title')->find($post['id']);

        $store_goods['title'] ? $this->title = '移动清单-' . $store_goods['name'] . '（' . $store_goods['title'] . '）' : $this->title = '移动清单-' . $store_goods['name'];

        $db = Db::name('store_goods_log')->order('id', 'desc')->where('store_id',$store_id)->where('goods_spec_id', $post['goods_spec_id'])->where('goods_id', $post['goods_id']);

        return parent::_list($db);
    }


    /**
     * 设置安全库存
     * @return array|string
     */
    public function edit()
    {
        return $this->_form('store_goods_stock', 'edit');
    }

    /**
     * 报损
     * @return array|string
     */
    public function loss()
    {
        $store_id = session('user')['store_id'];

        if (request()->ispost()) {
            $post = input('post.');
            $material_stock = db('store_goods_stock')->find($post['id']);
            $chengben = $material_stock['chengben_price']*$post['loss'];

            $stock = db('store_goods_stock')->where('id', $post['id'])->setDec('stock', $post['loss']);
            $log = db('store_goods_log')->insert(['store_id' => $store_id, 'goods_id' => $material_stock['goods_id'],'types'=>0, 'sunhao_num' => $post['loss'], 'cur_stock' => $material_stock['stock'] - $post['loss'], 'addtime' => time(), 'remark' => $post['reason'], 'goods_spec_id' => $material_stock['goods_spec_id'], 'title' => $material_stock['spec_title'],'chengben'=>$chengben]);

            if ($stock !== false && $log !== false)
                $this->success('商品报损成功！', '');
        } else {
            return $this->_form('store_goods_stock', 'loss');
        }
    }

    /**
     * 调价
     * @return array|string
     */
    public function price()
    {
        $id = input('id');
        if (request()->ispost()) {
            $post = input('post.');

            $stock = db('store_goods_stock')->where('id', $post['id'])->update(['trim_price' => $post['trim_price']]);

            if ($stock !== false)
                $this->success('价格设置成功！', '');
        } else {
            $store_goods = db('store_goods_stock')->where('id', $id)->find();

            $this->assign('store_goods', $store_goods);

            return $this->_form('store_goods_stock', 'price');
        }
    }

    /**
     * 一键调价
     */
    public function change()
    {
        $store_id = session('user')['store_id'];

        if (request()->ispost()) {
            $post = input('post.');

            if (isset($post['open']))
                $price_status = 1;
            else
                $price_status = 0;

            $time = explode(' - ', $post['time']);

            $stock = db('store')->where('id', $store_id)->update(['begin' => strtotime($time[0]), 'end' => strtotime($time[1]), 'price_status' => $price_status]);

            if ($stock !== false)
                $this->success('设置成功！', '');
        } else {
            $store = db('store')->find($store_id);

            $this->assign('store', $store);

            return $this->_form('store', 'change');
        }

    }


    /**
     * 库存日志
     * @return array|string
     */
    public function log()
    {
        $this->title = '库存日志';

        $store_id = session('user')['store_id'];

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT'],
        ];

        $db = Db::name('store_goods_log')->where('store_id', $store_id)->alias('a')->order('a.id', 'desc')->join($join)->field('a.*,g.*,d.*,g.id as gid,a.addtime as atime');

        $get = $this->request->get();

        if (isset($get['name']) && $get['name'] !== '')
            $db->whereLike('g.name', '%' . $get['name'] . '%');

        if (isset($get['export']))
            $this->down($db->select());
        else
            return parent::_list($db);
    }


    /**
     * 导出
     * @param $data
     */
    public function down($data)
    {
        $filename = '库存日志'.date('YmdHis').'.xls';

        $objPHPExcel = new PHPExcel();//新建一个表
        $objSheet = $objPHPExcel->getActiveSheet();//获得当前活动Sheet
        $objSheet->setTitle("库存日志");

        $objSheet
            ->setCellValue('A1', '商品ID')
            ->setCellValue('B1', '商品名称')
            ->setCellValue('C1', '商品属性')
            ->setCellValue('D1', '入库')
            ->setCellValue('E1', '出库')
            ->setCellValue('F1', '报损')
            ->setCellValue('G1', '结存')
            ->setCellValue('H1', '备注')
            ->setCellValue('I1', '时间');//填充

        $j = 2;

        foreach ($data as $key => $value) {

            $objSheet
                ->setCellValue('A' . $j, $value['gid'])
                ->setCellValue('B' . $j, $value['name'])
                ->setCellValue('C' . $j, $value['title'])
                ->setCellValue('D' . $j, $value['ruku_num'])
                ->setCellValue('E' . $j, $value['chuku_num'])
                ->setCellValue('F' . $j, $value['sunhao_num'])
                ->setCellValue('G' . $j, $value['cur_stock'])
                ->setCellValue('H' . $j, $value['remark'])
                ->setCellValue('I' . $j, date('Y-m-d H:i:s', $value['atime']));

            $j ++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $objWriter->save("php://output");
    }



    /**
     * 商品库存
     * @return array|string
     */
    public function stock()
    {
        $this->title = '商品库存';
        $get = $this->request->get();

        $join = [
            ['ys_goods g', 'a.goods_id=g.id', 'LEFT'],
            ['ys_goods_spec_detail d', 'a.goods_spec_id=d.id', 'LEFT'],
            ['ys_goods_category c', 'g.cat_id=c.id', 'LEFT'],
            ['ys_goods_label b ','a.goods_sign=b.id','LEFT']
        ];

        $store_id = session('user')['store_id'];

        $db = Db::name('store_goods_stock')->alias('a')->where('a.store_id', $store_id)->field('a.*,g.name,c.title as ctitle,g.logo,g.id as gid,d.title as dtitle,d.price dprice,b.sign')->order('a.id desc,g.id')->where(['a.is_deleted'=>0,'is_diannei'=>0])->join($join)->order('id desc');

        foreach (['name'] as $key) {
            (isset($get[$key]) && $get[$key] !== '') && $db->whereLike($key, "%{$get[$key]}%");
        }

        $qiniu = config('qiniu');
        $this->assign('qiniu', $qiniu['yangshi']);          //七牛样式后缀

        $store = db('store')->find($store_id);

        $this->assign('store', $store);

//        $warn = db('store_goods_stock')->where('')->select();
//        $num = 0;//报警
//        foreach ($warn as $value)
//            if ($value['stock'] < $value['warn_stock'])
//                $num++;

        $num = db('store_goods_stock')->where(['store_id'=>$store_id,'is_deleted'=>0,'is_diannei'=>0])->where('stock','lt','warn_stock')->count();

        if ($num > 0) {
            $this->assign('num', $num);
        }else{
            $num = 0;
        }

        if (isset($get['export']))
            $this->downstock($db->select());
        else
            return parent::_list($db);

    }

    /**
     * @Author  lingyun
     * @Desc    设置商品标签
     */
    public function set_goods_label(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            //设置标签的商品
            $goods = db('store_goods_stock')->where('id',$post['id'])->find();
            if(!empty($post['goods_label'])){
                $post['goods_label'] = implode(',',$post['goods_label']);
            }else{
                $post['goods_label'] = '';
            }

            //更新所有的标签
            $where = [
                'store_id'=>$goods['store_id'],
                'goods_id'=>$goods['goods_id']
            ];
            db('store_goods_stock')->where($where)->update(['goods_label'=>$post['goods_label']]);
            //更新所有的标签

            $res = db('store_goods_stock')->where('id',$post['id'])->update(['goods_label'=>$post['goods_label']]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }
        $id = input('id');
        $where_goods_label = [
            'status'=>1,
            'is_deleted'=>0
        ];
        $goods = db('store_goods_stock')->where('id',$id)->value('goods_label');
        if(!empty($goods)){
            $goods = explode(',',$goods);
        }else{
            $goods = array();
        }
        $this->assign('goods',$goods);
        $goods_label = db('goods_label')->where($where_goods_label)->select();
        $this->assign('goods_label',$goods_label);
        $this->assign('id',$id);
        return $this->fetch('set_goods_label');
    }

    /**
     * @Author  lingyun
     * @Desc    设置商品的标志
     */
    public function set_goods_sign(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $goods = db('store_goods_stock')->where('id',$post['id'])->find();
            $res = db('store_goods_stock')->where(['goods_id'=>$goods['goods_id'],'store_id'=>$goods['store_id']])->update(['goods_sign'=>$post['goods_sign']]);
            $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $id = input('id');
            $goods = db('store_goods_stock')->where('id',$id)->find();

            //商品标签
            $sign = db('goods_label')->where(['status'=>1,'is_deleted'=>0])->select();
            $this->assign('id',$id);
            $this->assign('sign',$sign);
            $this->assign('goods',$goods);
            return $this->fetch('set_goods_sign');
        }
    }


    public function downstock($data)
    {
        $filename = '库存列表'.date('YmdHis').'.xls';

        $objPHPExcel = new PHPExcel();//新建一个表
        $objSheet = $objPHPExcel->getActiveSheet();//获得当前活动Sheet
        $objSheet->setTitle("库存列表");

        $objSheet
            ->setCellValue('A1', '商品ID')
            ->setCellValue('B1', '商品分类')
            ->setCellValue('C1', '商品名称')
            ->setCellValue('D1', '状态(0下架1上架)')
            ->setCellValue('E1', '商品属性')
            ->setCellValue('F1', '库存')
            ->setCellValue('G1', '安全库存')
            ->setCellValue('H1', '线下优惠价格');

        $j = 2;

        foreach ($data as $key => $value) {

            $objSheet
                ->setCellValue('A' . $j, $value['gid'])
                ->setCellValue('B' . $j, $value['ctitle'])
                ->setCellValue('C' . $j, $value['name'])
                ->setCellValue('D' . $j, $value['onsale'])
                ->setCellValue('E' . $j, $value['dtitle'])
                ->setCellValue('F' . $j, $value['stock'])
                ->setCellValue('G' . $j, $value['warn_stock'])
                ->setCellValue('H' . $j, $value['trim_price']);

            $j ++;
        }

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $objWriter->save("php://output");
    }

}